import './index.css';
import {useCallback, useContext, useState} from "react";
import StuContext from "../../store/StuContext";
import useFetch from "../../hooks/useFetch";

const StudentForm = (props) => {
	const [inputData, setInputData] = useState({
		name: props.stu ? props.stu.name : '',
		gender: props.stu ? props.stu.gender : '男',
		age: props.stu ? props.stu.age : '',
		address: props.stu ? props.stu.address : '',
	});

	const ctx = useContext(StuContext);

	const nameChangeHandler = (e) => {
		setInputData(prevState => (
		{...prevState, name: e.target.value}
		))
	};

	const genderChangeHandler = (e) => {
		setInputData(prevState => (
			{...prevState, gender: e.target.value}
		))
	}

	const ageChangeHandler = (e) => {
		setInputData(prevState => (
			{...prevState, age: +e.target.value}			// 注意age是number类型, +e.target.value 将其转成 number类型
		))
	}

	const addressChangeHandler = (e) => {
		setInputData(prevState => (
			{...prevState, address: e.target.value}
		))
	}


	const {loading, error, fetchData: saveStudent} = useFetch({
		url: props.stu ? `students/${props.stu.documentId}` : "students",
		method: props.stu ? "put" : "post",
	}, ctx.fetchData);

	// 添加按钮点击
	const submitHandler = () => {
		saveStudent(inputData);
	}

	// 修改学生
	const updateHandler = () => {
		saveStudent(inputData);
	}

	return (
		<>
			<tr className={"student-form"}>
				<td><input type="text" onChange={nameChangeHandler} value={inputData.name} /></td>
				<td>
					<select onChange={genderChangeHandler} value={inputData.gender}>
						<option value="男">男</option>
						<option value="女">女</option>
					</select>
				</td>
				<td><input type="text" onChange={ageChangeHandler} value={inputData.age} /></td>
				<td><input type="text" onChange={addressChangeHandler} value={inputData.address} /></td>

				<td>
					{props.stu &&
						<>
							<button onClick={() => props.onCancel()}>取消</button>
							<button onClick={updateHandler}>确定</button>
						</>
					}
					{!props.stu &&
						<><button onClick={submitHandler}>添加</button></>
					}
				</td>


			</tr>
			{loading && <tr><td colSpan={5}>添加中...</td></tr>}
			{error && <tr><td colSpan={5}>添加失败</td></tr>}
		</>
	)
}

export default StudentForm;